﻿@model App.Web.ViewModels.TransactionViewModel
@using App.Web.Utility
@using App.Core.Extensions;
@{
    //String ReqFrom = ViewData[AppConstants.ViewDataKeys.SUB_MODEL] as String;
    //bool _IsIssue = ViewData[AppConstants.ViewDataKeys.SUB_MODEL] != null ? true : false; 
    bool _IsIssue = Model.IsIssue.ToBoolean() ? true : false;
    bool _IsPosted = Model.IsPosted.ToBoolean()  ? true : false;   
    
    String pageTitle = _IsIssue ? "Issue Products" : "Receive Products";
    ViewBag.Title = Html.GetPageTitle(pageTitle);
    int companyID = SessionCache.CurrentUser.Company.ID;
    HtmlString json = new HtmlString(BindSelectList.ProductQuality().ToJSON());
    App.Domain.AppEntities _Context = new App.Domain.AppEntities();
    List<App.Web.ViewModels.UOMViewModel> uoms = AutoMapper.Mapper.Map<List<App.Domain.UOM>, List<App.Web.ViewModels.UOMViewModel>>(_Context.UOMs.ToList());
    HtmlString uomJson = new HtmlString(uoms.ToJSON());
    List<App.Domain.Product> _Products = (from P in _Context.Products.Include("UOM") where P.CompanyID == companyID && P.IsActive && !P.IsDeleted orderby P.Name select P).ToList();
}

@section PageHeadSection
{
    <style type="text/css">
        .product-list{width:100%; border-collapse:collapse; margin-bottom:10px;}
        .product-list img{cursor:pointer;}
        .product-list th{text-align:left;}
        .product-list td{border:#EFEFEF 1px solid;}
        .product-list select{width:100%;}
        .product-list input{width:100%;}        
    </style>
}

<div class="page-heading">
    <h1>@pageTitle</h1>
    <div>
        @if (_IsIssue){
            <text>Issue Product. Enter necessary transaction information and add products to your inventory.</text>
        }
        else {
            <text> Receive products. Enter necessary transaction information and add products to your inventory.<br />
            For initial entry adjust your product quantity.</text>
        }
    </div>
</div>

@Html.JavaScript("jquery.validate.min.js", Url)
@Html.JavaScript("jquery.validate.unobtrusive.min.js", Url)
@Html.Partial("_DatePicker")

<div class="GroupBox">	
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)

    if (Model == null)
    {
        @: @Html.ErrorMessageBox("Sorry! Requested Transaction was not found for edit.")
    }
    else
    {
		@Html.HiddenFor(model => model.ID)
        <h2 class="section-heading">Basic Transaction Information</h2>
        <div style="margin-top:10px;"></div>
		<div class="editor-label">
            @Html.LabelFor(model => model.Code)			
		</div>
		<div class="editor-field">
            <span id="lblCode">@Model.Code</span>
			@*@Html.EditorFor(model => model.Code)
			@Html.ValidationMessageFor(model => model.Code)*@
            @Html.HiddenFor(model => model.Code)
		</div>
        <div class="editor-label">
			@Html.LabelFor(model => model.StoreID)
		</div>
		<div class="editor-field">
            @Html.DropDownListFor(model => model.StoreID, BindSelectList.Stores(companyID))			
			@Html.ValidationMessageFor(model => model.StoreID)
		</div>
		<div class="editor-label">
			@Html.LabelFor(model => model.TransactionDate)
		</div>
		<div class="editor-field">
			@Html.TextBoxFor(model => model.TransactionDate, new { @class = "datepicker" })
			@Html.ValidationMessageFor(model => model.TransactionDate)
		</div>
        <div class="editor-label">
			@Html.LabelFor(model => model.ReferenceNo)
		</div>
		<div class="editor-field">
			@Html.EditorFor(model => model.ReferenceNo)
			@Html.ValidationMessageFor(model => model.ReferenceNo)
		</div>    
		<div class="editor-label">
			@Html.LabelFor(model => model.Description)
		</div>
		<div class="editor-field">
			@Html.TextAreaFor(model => model.Description)
			@Html.ValidationMessageFor(model => model.Description)
		</div>
    
        <h2 class="section-heading">Transaction Details</h2>
        <div style="margin:10px 0px 10px 0px;">
            <div class="button float-left" onclick="AddNewProduct();">Add Product</div>
            <div class="button float-left" onclick="PostItems(this);" style="margin-left:10px; background-color:#EFEFEF; color:#878686;">Post Transaction</div>
            @*<div class="float-right">
                <input type="checkbox" value="Post" id="chkPost" onclick="PostItems(this);" /><label for="chkPost">Post Transaction</label>
            </div>*@
            <div class="clear"></div>
        </div>
        <table cellpadding="3" cellspacing="0" class="product-list">
            <tbody id="tbdProductList">               
                <tr>
                    <th style="width:5%;">Serial</th>
                    <th style="width:30%;">Product</th>
                    <th style="width:10%;">Quality</th>                    
                    <th style="width:10%;">Quantity</th>
                    <th style="width:10%;">UOM</th>
                    <th style="width:10%;">Unit Price</th>
                    <th>Comment</th>
                    <th style="width:2%;"></th>
                </tr>
                @for (int i = 0; i < Model.TransactionDetails.Count; i++)
                {
                    var detail = Model.TransactionDetails[i];
                <tr>                        
                    <td class="center-text"><span class="txt-serial">@(i + 1)</span><input type="hidden" class="hdn-detail-id" value="@detail.ID" /></td>
                    <td>
                        <select class="ddl-product">
                            <option value="0" uom-id="0">Select</option>
                            @foreach (var product in _Products)
                            {
                            <option value="@product.ID" uom-id="@product.UomID.GetValueOrDefault()"@if (detail.ProductID == product.ID)
                                                                                                   {<text> selected="selected"</text>}>@product.Name</option>
                            }
                        </select>
                    </td>
                    <td>
                        <select class="ddl-quality">                
                            @foreach (var quality in BindSelectList.ProductQuality("Select"))
                            {
                            <option value="@quality.Value" @if (detail.ItemQuality == quality.Value)
                                                           {<text> selected="selected"</text>}>@quality.Text</option>
                            }
                        </select>
                    </td>                    
                    <td><input class="txt-quantity" type="text" value="@detail.ReceiveQuantity"/></td>
                    <td class="txt-uom">@_Products.FirstOrDefault(P => P.ID == detail.ProductID).UOM.Name</td>
                    <td><input class="txt-unit-price" type="text" value="@detail.UnitPrice"/></td>
                    <td><input class="txt-comment" type="text" value="@detail.Description" maxlength="180" /></td>
                    <td><img src="/content/images/delete.png" alt="Delete Item" title="Delete Item" onclick="ConformDeleteDialog(this);" /></td>
                </tr>
                }
            </tbody>
            <tbody id="tbdTemplate" class="hidden">
                <tr>
                    <td class="center-text"><span class="txt-serial"></span><input type="hidden" class="hdn-detail-id" value="" /></td>
                    <td>
                        <select class="ddl-product">
                            <option value="0" uom-id="0">Select</option>
                            @foreach (var product in _Products)
                            {
                            <option value="@product.ID" uom-id="@product.UomID.GetValueOrDefault()">@product.Name</option>
                            }
                        </select>
                    </td>
                    <td>
                        <select class="ddl-quality">                
                            @foreach (var quality in BindSelectList.ProductQuality("Select"))
                            {
                            <option value="@quality.Value" @if (quality.Value == "G")
                                                           { <text>selected="selected"</text>}>@quality.Text</option>
                            }
                        </select>
                    </td>                    
                    <td><input class="txt-quantity" type="text" value=""/></td>
                    <td class="txt-uom"></td>
                    <td><input class="txt-unit-price" type="text" value=""/></td>
                    <td><input class="txt-comment" type="text" value="" /></td>
                    <td><img src="/content/images/delete.png" alt="Delete Item" title="Delete Item" onclick="ConformDeleteDialog(this);" /></td>
                </tr>
            </tbody>
        </table>
    
        <div id="deleteDialog" style="display:none;">
            Do you really want to delete this transaction details?
        </div>
    
        <div class="bm-dialog"  id="divMessageBox" style="display:none">
            <div>            
                <div class="bm-dialog-title">Confirmation</div>
            </div>
            <div class="bm-dialog-body" style="min-height:60px;" id="dvMsg">
                             
            </div>
            <div class="bm-dialog-button" style="height:15px;"></div>
        </div>
    
        <div id="divUOM" class="hidden">@uomJson</div>
        <script type="text/javascript" language="javascript">

            var _tranDetail; 
            
            function ConformDeleteDialog(imgDelete) {
                _tranDetail = imgDelete;
                $('#deleteDialog').dialog('open');
            }

            
            var _UOMs = eval($('#divUOM').html());
            $(document).ready(function () {
                $('#deleteDialog').dialog({
                    autoOpen: false, width: 400,
                    buttons: {
                        'Ok': function () { DeleteItem(_tranDetail); $(this).dialog("close"); },
                        'Cancel': function () { $(this).dialog("close"); }
                    }
                });

                $('#tbdProductList .ddl-product').live('change', function () {
                    $(this).parent().parent().find('td.txt-uom').html(GetSelectedUomText($('option:selected', this).attr('uom-id')));
                    $(this).removeClass('input-validation-error');
                    if($(this).val() <= 0)
                        $(this).addClass('input-validation-error');
                });
                $('#tbdProductList .ddl-quality').live('change', function () {
                    $(this).removeClass('input-validation-error');
                    if ($(this).val() <= 0)
                        $(this).addClass('input-validation-error');
                });
                $('#tbdProductList .txt-unit-price,#tbdProductList .txt-quantity').live('blur', function () {
                    $(this).removeClass('input-validation-error');
                    if (!IsNumeric($(this).val()))
                        $(this).addClass('input-validation-error');
                });
            });
            function GetSelectedUomText(uomID) {                
                for (var i = 0; i < _UOMs.length; i++) {
                    if (_UOMs[i].ID == uomID)
                        return _UOMs[i].Name;
                }
                return '';
            }
            function AddNewProduct() {
                var tblList = $('#tbdProductList');
                var html = $('#tbdTemplate').html();
                $(tblList).append(html);
                $(tblList).find('tr').each(function (i, tr) { $(tr).find('span.txt-serial').html(i); });
            }
            function Transaction(id, description, code, referenceNo, transactionDate, storeID)
            {
                this.ID = id;
                this.Description = description;
                this.Code = code;
                this.ReferenceNo = referenceNo;
                this.TransactionDate = transactionDate;
                this.StoreID = storeID;
                this.TransactionDetails = [];
            }
            function BuildObjectsForSave() {
                var transaction = new Transaction($('#ID').val(), $('#Description').val(), $('#Code').val(), $('#ReferenceNo').val(), $('#TransactionDate').val(), $('#StoreID').val())
                $('#tbdProductList tr').each(function (i, tr) {                    
                    if (i > 0) {
                        var transactionDetailID = $(tr).find('.hdn-detail-id').val();
                        if (transactionDetailID == undefined || transactionDetailID == null || transactionDetailID.length <= 0)
                            transactionDetailID = 0;
                        var lineItem =
                        {
                            ID: transactionDetailID, ProductID: $(tr).find('.ddl-product').val(), ItemQuality: $(tr).find('.ddl-quality').val(), ReceiveQuantity: $(tr).find('.txt-quantity').val(),
                            UnitPrice: $(tr).find('.txt-unit-price').val(), Description: $(tr).find('.txt-comment').val()
                        };
                        transaction.TransactionDetails.push(lineItem);
                    }
                });
                return transaction;
            }
            function BindTransaction(transaction) {
                $('#lblCode').html(transaction.Code);
                $('#Code').val(transaction.Code);
                $('#ID').val(transaction.ID);
                var trs = $("#tbdProductList").find("tr:gt(0)");
                var tblList = $('#tbdProductList');                
                for(var i = 0; i < transaction.TransactionDetails.length; i++){
                    var detail = transaction.TransactionDetails[i];
                    var tr = trs[i];
                    $(tr).find('span.txt-serial').html(i + 1);
                    $(tr).find('.hdn-detail-id').val(detail.ID);                    
                }                
            }
            function SaveTransaction() {
                if (IsValidInput()) {
                    ShowLoadingAnimation(false);
                    var transaction = BuildObjectsForSave();                    
                    @if(_IsIssue) {
                        <text>var url = '/private/inventory/issue';</text>
                    }
                    else{
                        <text>var url = '/private/inventory/receive';</text>
                    }
                    Ajax(url, 'json=' + JSON.stringify(transaction), function (result) {
                        var savedTransaction = eval('(' + result + ')');
                        BindTransaction(savedTransaction);
                        HideLoadingAnimation();
                        ShowDialogMessage('Your Transaction Details Saved Successfully');
                    });
                }
            }

            function ShowDialogMessage(Message) {
                var $msgDiv = $('#dvMsg');
                $msgDiv.show().html(Message);

                var $messageDiv = $('#divMessageBox');
                $messageDiv.show();
                setTimeout(function () { $messageDiv.hide(); }, 3000);
            }

            function IsValidInput() {                
                if ($('form').valid()) {
                    var trs = $("#tbdProductList").find("tr:gt(0)");
                    if (trs.length <= 0)
                        return false;
                    var result = true;
                    for (var i = 0; i < trs.length; i++) {
                        var tr = trs[i];
                        var ddlProduct = $(tr).find('.ddl-product');
                        var ddlQuality = $(tr).find('.ddl-quality');
                        var txtQuantity = $(tr).find('.txt-quantity');
                        var txtUnitPrice = $(tr).find('.txt-unit-price');
                        if ($(ddlProduct).val() <= 0) {
                            $(ddlProduct).addClass('input-validation-error');
                            result = false;
                        }
                        if ($(ddlQuality).val().length <= 0) {
                            $(ddlQuality).addClass('input-validation-error');
                            result = false;
                        }
                        if (!IsNumeric($(txtQuantity).val())) {                        
                            $(txtQuantity).addClass('input-validation-error');
                            result = false;
                        }
                        if (!IsNumeric($(txtUnitPrice).val())) {
                            $(txtUnitPrice).addClass('input-validation-error');
                            result = false;
                        }
                    }
                    return result;
                }                
                return false;
            }
            function DeleteItem(imgDelete) {
                var detailId = $(imgDelete).parent().parent().find('.hdn-detail-id').val();
                if (detailId > 0) {
                    ShowLoadingAnimation(false);
                    Ajax('/private/inventory/delete', 'detailId=' + detailId, function () {
                        HideLoadingAnimation();
                    });
                    //Ajax('/private/inventory/delete', 'detailId=' + detailId, Delete_Success); 
                }
                $(imgDelete).parent().parent().fadeOut('slow', function () { $(this).remove(); })

            }

            function ShowDialogMessage(Message) {
                var $msgDiv = $('#dvMsg');
                $msgDiv.show().html(Message);

                var $messageDiv = $('#divMessageBox');
                $messageDiv.show();
                setTimeout(function () { $messageDiv.hide(); }, 3000);
            }
            
            function PostItems(chkPost) {
                
            }
        </script>
    
		@*@Html.HiddenFor(model => model.CreatedOn)
		@Html.HiddenFor(model => model.CreatebBy)
		@Html.HiddenFor(model => model.ModifiedOn)
		@Html.HiddenFor(model => model.ModifiedBy)*@
		<div> 
            <input type="button" value="Save" onclick="SaveTransaction();" />
			@*<input type="submit" value="Save" />*@ 
            
            
            @if (_IsIssue)
            {

                if (_IsPosted)
                {
                    <a href="/private/inventory/List?type=Issue&posted=Yes">Back to List</a>
                }
                else
                {
                    <a href="/private/inventory/List?type=Issue&posted=No">Back to List</a>
                }
            }
            else
            {
                if (_IsPosted)
                {
                    <a href="/private/inventory/List?type=Receive&posted=Yes">Back to List</a>
                }
                else
                {
                    <a href="/private/inventory/List?type=Receive&posted=No">Back to List</a>
                }
            }

            @*@Html.ActionLink("Back to List", "List")*@
            @*<li><a href="/private/inventory/list?reqFrom="+@ReqFrom+"">Back to List</a></li>*@
		</div>		
    }
}
</div>